package com.sddnytsh.body_buildingsystem.components

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.utils.navigatePostDetail
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.data.state.UserState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

@Composable
fun Page1(navController: NavController) {
    var posts by remember { mutableStateOf<List<CommunityPost>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    // 🔥 添加缓存机制 - 避免重复加载
    var hasLoaded by remember { mutableStateOf(false) }
    var lastLoadTime by remember { mutableStateOf(0L) }
    val CACHE_DURATION = 180000L // 180秒缓存，进一步减少重复请求

    // 定义颜色方案
    val primaryColor = Color(0xFF4361EE)
    val secondaryColor = Color(0xFF3A0CA3)
    val lightBackground = Color(0xFFF8F9FA)
    val cardColor = Color.White
    val textPrimary = Color(0xFF212529)
    val textSecondary = Color(0xFF6C757D)

    LaunchedEffect(Unit) {
        // 🔥 检查缓存 - 避免重复加载
        val currentTime = System.currentTimeMillis()
        if (hasLoaded && (currentTime - lastLoadTime) < CACHE_DURATION) {
            Log.d("Page1", "🔥 使用缓存数据，跳过网络请求")
            isLoading = false
            return@LaunchedEffect
        }
        
        try {
            Log.d("Page1", "🔥 开始加载帖子数据")
            val postData = fetchPostData()
            postData?.let {
                posts = it
                hasLoaded = true
                lastLoadTime = currentTime
                Log.d("Page1", "🔥 帖子数据加载完成，共${it.size}条")
            }
            isLoading = false
        } catch (e: Exception) {
            errorMessage = "加载失败: ${e.message}"
            isLoading = false
            Log.e("Page1", "🔥 帖子数据加载失败: ${e.message}")
        }
    }

    // 下拉刷新状态
    val refreshScope = rememberCoroutineScope()
    var refreshing by remember { mutableStateOf(false) }

    fun refresh() = refreshScope.launch {
        refreshing = true
        try {
            Log.d("Page1", "🔥 手动刷新帖子数据")
            val postData = fetchPostData()
            postData?.let {
                posts = it
                hasLoaded = true
                lastLoadTime = System.currentTimeMillis()
                Log.d("Page1", "🔥 帖子数据刷新完成，共${it.size}条")
            }
        } catch (e: Exception) {
            errorMessage = "刷新失败: ${e.message}"
            Log.e("Page1", "🔥 帖子数据刷新失败: ${e.message}")
        } finally {
            refreshing = false
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(lightBackground)
    ) {
        // 顶部栏 - 使用渐变背景
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(64.dp)
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(primaryColor, secondaryColor)
                    )
                )
                .padding(horizontal = 16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxSize(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "💬 运动社区",
                    color = Color.White,
                    style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
                    modifier = Modifier.weight(1f)
                )

                IconButton(
                    onClick = { refresh() },
                    modifier = Modifier.size(40.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Refresh,
                        contentDescription = "刷新",
                        tint = Color.White
                    )
                }
            }
        }

        if (isLoading) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 添加加载图标背景
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .background(
                                primaryColor.copy(alpha = 0.1f),
                                CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = primaryColor,
                            modifier = Modifier.size(48.dp)
                        )
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "正在加载社区动态...",
                        color = textSecondary,
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
            }
        } else if (errorMessage != null) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 错误图标背景
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .background(
                                Color(0xFFE57373).copy(alpha = 0.1f),
                                CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Default.Warning,
                            contentDescription = "错误",
                            tint = Color(0xFFE57373),
                            modifier = Modifier.size(40.dp)
                        )
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "加载失败",
                        style = MaterialTheme.typography.titleMedium.copy(
                            fontWeight = FontWeight.Bold,
                            color = textPrimary
                        )
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = errorMessage ?: "网络连接异常",
                        color = textSecondary,
                        textAlign = TextAlign.Center,
                        modifier = Modifier.padding(horizontal = 32.dp)
                    )
                    Spacer(modifier = Modifier.height(24.dp))
                    Button(
                        onClick = { refresh() },
                        colors = ButtonDefaults.buttonColors(containerColor = primaryColor),
                        shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
                        modifier = Modifier.height(48.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Refresh,
                            contentDescription = "重试",
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("重新加载", fontWeight = FontWeight.Medium)
                    }
                }
            }
        } else if (posts.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 空状态图标背景
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .background(
                                primaryColor.copy(alpha = 0.1f),
                                CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "💬",
                            style = MaterialTheme.typography.titleLarge
                        )
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "暂无帖子",
                        style = MaterialTheme.typography.titleMedium.copy(
                            fontWeight = FontWeight.Bold,
                            color = textPrimary
                        )
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "快来发表第一篇帖子吧",
                        style = MaterialTheme.typography.bodyMedium.copy(
                            color = textSecondary
                        )
                    )
                    Spacer(modifier = Modifier.height(24.dp))
                    Button(
                        onClick = {
                            navController.navigate("createPost")
                        },
                        colors = ButtonDefaults.buttonColors(containerColor = primaryColor),
                        shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
                        modifier = Modifier.height(48.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Add,
                            contentDescription = "发帖",
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("发表帖子", fontWeight = FontWeight.Medium)
                    }
                }
            }
        } else {
            // 使用SwipeRefresh实现下拉刷新
            SwipeRefresh(
                state = rememberSwipeRefreshState(refreshing),
                onRefresh = { refresh() },
                modifier = Modifier.fillMaxSize()
            ) {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(horizontal = 16.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    item {
                        Spacer(modifier = Modifier.height(16.dp))
                    }

                    items(posts) { post ->
                        PostItem(
                            post = post,
                            onPostClick = { clickedPost ->
                                navController.navigatePostDetail(clickedPost.id.toInt())
                            },
                            onLikeClick = { clickedPost ->
                                // 处理点赞逻辑
                            },
                            onFavoriteClick = { clickedPost ->
                                // 处理收藏逻辑
                            },
                            onCommentClick = { clickedPost ->
                                // 评论功能现在直接在PostItem中处理
                            }
                        )
                    }

                    item {
                        Spacer(modifier = Modifier.height(16.dp))
                        // 加载更多提示
                        if (posts.isNotEmpty()) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "没有更多内容了",
                                    color = textSecondary.copy(alpha = 0.6f),
                                    style = MaterialTheme.typography.bodySmall
                                )
                            }
                        }
                    }
                }
            }
        }

        // 底部悬浮按钮
        if (!isLoading && errorMessage == null) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(24.dp),
                contentAlignment = Alignment.BottomEnd
            ) {
                FloatingActionButton(
                    onClick = {
                        navController.navigate("createPost")
                    },
                    containerColor = primaryColor,
                    contentColor = Color.White,
                    modifier = Modifier
                        .size(56.dp)
                        .shadow(8.dp, CircleShape)
                ) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "发帖",
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
    }
}

private suspend fun fetchPostData(): List<CommunityPost> {
    data class PostListApiResponse<T>(
        val success: Boolean,
        val data: T
    )

    data class NestedData(
        val posts: List<CommunityPost>
    )

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
    val currentUserId = UserState.currentUserId
    val url = if (currentUserId != null) {
        "${NetworkConfig.BASE_URL}/api/community-posts?currentUserId=$currentUserId"
    } else {
        "${NetworkConfig.BASE_URL}/api/community-posts"
    }

    val request = Request.Builder()
        .url(url)
        .build()

    return withContext(Dispatchers.IO) {
        try {
            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    val responseBody = response.body?.string()
                    if (!responseBody.isNullOrBlank()) {
                        val gson = Gson()
                        val apiResp: PostListApiResponse<NestedData> = gson.fromJson(
                            responseBody,
                            object : TypeToken<PostListApiResponse<NestedData>>() {}.type
                        )
                        if (apiResp.success) apiResp.data.posts else emptyList()
                    } else {
                        emptyList()
                    }
                } else {
                    emptyList()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            emptyList()
        }
    }
}